#!/bin/sh
# Copyright (c) 2007, Technologic Systems.
# All rights reserved.
#
# Roots to SD flash card, assumes partition #3 (/dev/sdcard0/disc0/part3)
# symlink to /linuxrc and run "save" to use

export PATH=/bin:/sbin:/lbin:/mnt/root/bin:/mnt/root/sbin:/mnt/root/usr/bin:/mnt/root/usr/sbin:/mnt/root/usr/local/bi
n:/mnt/root/usr/local/sbin
export LD_LIBRARY_PATH=/lib:/usr/lib
export CONSOLE=/dev/ttyS0


mount -t proc none /proc
mount -t sysfs none /sys
mount -t tmpfs none /dev
mdev -s
mkdir /dev/pts /dev/shm
mount -t devpts none /dev/pts
mount -t tmpfs none /dev/shm

setconsole $CONSOLE
stty -F $CONSOLE ospeed 115200 > /dev/null 2>&1
hostname ts7800
check-usb-update >/dev/null 2>&1 </dev/null &

echo ">> Booting to SD Card...." > $CONSOLE

(
  insmod /tssdcard.ko
  mdev -s
  if [ -e /dev/tssdcardb4 -a -e /mnt/root/notrootfs ]; then
    mount -o ro /dev/tssdcardb4 /mnt/root
    fsck /dev/tssdcardb4
    mount -o remount,rw /mnt/root
  fi
) > /dev/null 2>&1

if [ -e /mnt/root/notrootfs -o -e /mnt/root/fastboot -o ! -e /mnt/root/sbin/init ]; then

  if [ -e /mnt/root/fastboot ]; then
    echo ">> File 'fastboot' found. Booting to initrd instead...." > $CONSOLE
  else
    echo ">> SD Card failed. Booting to initrd..." > $CONSOLE
  fi

  echo ">> Configuring eth0 ...." > $CONSOLE

  (
    ifconfig lo 127.0.0.1 up
    route add -net 127.0.0.0 netmask 255.0.0.0 lo
    ifconfig eth0 192.168.0.10 up
    route add default gateway 192.168.0.1 eth0
    /sbin/telnetd

    insmod /ts7800_nand.ko
    insmod /tsuart1.ko
    insmod /tsuart7800.ko
    mdev -s

    if [ -e /dev/mtdblock3 -a -e /mnt/root/notrootfs ]; then
      mount -t yaffs2 -o ro /dev/mtdblock3 /mnt/root
    fi
  ) > /dev/null 2>&1 &

  (
    export BOOTTIME=`mvtime`
    export ENV=/shinit
    exec /bin/cttyhack /bin/sh -i < $CONSOLE > $CONSOLE 2>&1
  )

  wait
  killall busybox telnetd > /dev/null 2>&1
  echo ">> Booting Linux..." > $CONSOLE
  cd /mnt/root
  pivot_root . ./initrd
  ./bin/mount -n --move ./initrd/sys ./sys
  ./bin/mount -n --move ./initrd/proc ./proc
  exec ./usr/sbin/chroot . ./sbin/init < .$CONSOLE > .$CONSOLE 2>&1

else
  #verify if there is a kernel and issue bootload command. if not, then:
  echo ">> Go through SDCard  ...." > $CONSOLE
  echo ">> Configuring eth0 ...." > $CONSOLE
  ifconfig eth0 up

  echo ">> Loading kernel modules ...." > $CONSOLE
  insmod /ts7800_nand.ko
  insmod /tsuart1.ko
  insmod /tsuart7800.ko
  mdev -s

  cd /mnt/root
  pivot_root . ./initrd
  ./bin/mount -n --move ./initrd/sys ./sys
  ./bin/mount -n --move ./initrd/proc ./proc
  exec ./usr/sbin/chroot . ./sbin/init < .$CONSOLE > .$CONSOLE 2>&1

fi


